<?php
/**
 * 前台控制器基类
 *
 * @author susy<susy.liang@ilongyuan.com.cn>
 */

namespace Home\Controller;
use Think\Controller;
use User\Api\UserApi;
use Common\Util\ThinkSDK\ThinkOauth;
use Api\Event\CacheEvent;

class HomeController extends Controller {

    protected $uinfo = '';

    /* 空操作，用于输出404页面 */
    public function _empty() {
        $this->redirect('/');
    }

    /**
     * 基础参数的初始化
     */
    protected function _initialize() {
        $Redis = CacheEvent::instance(0);
        load_config($Redis);
        unset($Redis);
        $this->_allow_origin();
        if ( !C( 'WEB_SITE_CLOSE' ) ) {
            $this->error( '站点已经关闭，请稍后访问~' );
        }
        define('IS_MOBILE', is_mobile_request());
        define('IS_WEIXIN', is_weixin());
        //探索
        // $tEvent = A( 'Api/Tag', 'Event' );
        // $this->tags = $tEvent->lists( 'id,title' );

        // $footerLimit    = C( 'HOME_FOOTER_LIMIT' );
        // $this->topicNav = A( 'Api/Topic', 'Event' )->getHomeTopics( true );
        // $this->gameNav  = A( 'Api/Game', 'Event' )->lists( '', 'id,name', $footerLimit );
        // $this->matchNav = A( 'Api/Match', 'Event' )->lists( 1, $footerLimit, false, 'id,title' );

        if (I('appToken')){
            $this->TokenLogin();
        }

        $uid = is_login( 1 );
        //add check the user auto login cookie info at 2015/7/7 by susy.liang<liangling@ilongyuan.com.cm>
        !$uid && $uid = $this->checkAutoLogin(); //取消在Home下判断  只放在入口判断
        //end
        if (I('demo')){
            print_r($_SESSION);exit;
        }
        define( 'UID', $uid );
        if ($uid) {
            
            $user = session( 'home_user_auth' );
            $this->uinfo = $userInfo = array(
                'id'=>$uid,
                'username'=>$user['username'],
                'nickname'=>$user['nickname'],
                'avatar' => $user['avatar'],
                'token' => $user['token']
            );
            $sso_channel = session('sso_channel');
            if ($sso_channel) {
                $userInfo['sso_channel'] = $sso_channel;
            }
            $this->assign( 'userInfo', $userInfo );

            //视频发布权限
            /*$submitVideo = A('Home/AccessUser')->accessControl('MyVideo/choose_game');
            $this->showSubmit = $submitVideo?1:0;*/

            if ( !$user['nickname'] && ACTION_NAME != 'nickname')
                $this->redirect( 'User/nickname');
        } else {
            $redirect_url = '';
            $sns = ThinkOauth::getInstance('sina');
            $sso_code_uri['sina'] = $sns->code($redirect_url);
            $sns = ThinkOauth::getInstance('qq');
            $sso_code_uri['qq'] = $sns->code();
            $sns = ThinkOauth::getInstance('weixin');
            $sso_code_uri['weixin'] = $sns->code($redirect_url);

            $this->assign('sso_code_uri', $sso_code_uri);
        }

        $sso = mobileBrower();
        $login_url = $sso ? U('user/ssologin') : U('user/login');
        $this->assign('login_url', $login_url);
        if (!IS_AJAX && !IS_MOBILE) {
            $this->assign('links', service('Links')->getTxtLists());
            /*
             * 网站header部分赛事游戏分类
             */
            $key = 'MATCH_GAMES_DATA';
            $Redis = CacheEvent::instance(0);
            $match_games = $Redis->get($key);
            if (empty($match_games)) {
                $match_games = event('match')->games();
                $Redis->setEx($key, 600, json_encode($match_games));
            } else {
                $match_games = json_decode($match_games, true);
            }
            unset($Redis);
            $this->match_games = $match_games;
        }
    }

    public function setRedirect()
    {
        cookie('redirect_url', curPageURL());
    }

    protected function TokenLogin()
    {
        $appToken = I('appToken', '', 'trim');
        $map = [
            'status'    => 1,
            'app_token' => $appToken,
        ];
        $uid = service('Token')->where($map)->find()['uid'] ?: 0;
        if ($uid){
            D('Member')->login($uid, $appToken);
        }
    }


    /**
    *检测用户自动登录的cookie信息
    *@author susy.liang<liangling@ilongyuan.com.cn>
    */
    // 修复自动登录bug
    // by liubo at 2016-05-26
    private function checkAutoLogin(){
        // 2015-7-20 11:30:32 Legend. 重写
        $uid = 0;
        $auto_login = cookie('auto_login',  '','prefix=login');
        if ($auto_login)
        {
            $salt = cookie('salt',      '','prefix=login');
            $token = cookie('token',     '','prefix=login');
            $username = cookie('auto_username', '','prefix=login');
            $user = service('Users')->detail($username, true); // 查询用户是否存在

            if (!$user)
            {
                return 0;
            }
            $cookie_auth = array(
                'salt'           => $salt,  // 加盐
                'auto_username'  => $username, 
                'key'            => C('API_AUTH_KEY'),   // 密钥
                'password'       => $user['password'],
            );

            if ($token === data_auth_sign($cookie_auth))
            {
                $user = D('Member')->login($user['id']);
                $uid = $user['id'];
            }
            else
            {
                $uid = 0;
            }
        }
        return $uid;
    }

    /* 用户登录检测 */
    protected function login() {
        /* 用户登录检测 */
        is_login() || $this->error( '您还没有登录，请先登录！', U( 'User/login' ) );
    }


    /**
     * 获取列表
     *
     * @author Legend. <xcx_legender@qq.com>
     * @param unknown
     * @return
     */
    protected function lists( $model, $where=array(), $order='', $base = array( 'status'=>array( 'egt', 0 ) ) ) {
        $options    =   array();
        $REQUEST    =   (array)I( 'request.' );
        if ( is_string( $model ) ) {
            $model  =   M( $model );
        }

        $OPT        =   new \ReflectionProperty( $model, 'options' );
        $OPT->setAccessible( true );

        $pk         =   $model->getPk();
        if ( $order===null ) {
            //order置空
        }else if ( isset( $REQUEST['_order'] ) && isset( $REQUEST['_field'] ) && in_array( strtolower( $REQUEST['_order'] ), array( 'desc', 'asc' ) ) ) {
                $options['order'] = '`'.$REQUEST['_field'].'` '.$REQUEST['_order'];
            }elseif ( $order==='' && empty( $options['order'] ) && !empty( $pk ) ) {
            $options['order'] = $pk.' desc';
        }elseif ( $order ) {
            $options['order'] = $order;
        }
        unset( $REQUEST['_order'], $REQUEST['_field'] );

        $options['where'] = array_filter( array_merge( (array)$base, /*$REQUEST,*/ (array)$where ), function( $val ) {
                if ( $val===''||$val===null ) {
                    return false;
                }else {
                    return true;
                }
            } );
        if ( empty( $options['where'] ) ) {
            unset( $options['where'] );
        }
        $options      =   array_merge( (array)$OPT->getValue( $model ), $options );
        $total        =   $model->where( $options['where'] )->count();

        if ( isset( $REQUEST['r'] ) ) {
            $listRows = (int)$REQUEST['r'];
        }else {
            $listRows = C( 'LIST_ROWS' ) > 0 ? C( 'LIST_ROWS' ) : 10;
        }
        $page = new \Think\Page( $total, $listRows, $REQUEST );
        if ( $total>$listRows ) {
            $page->setConfig( 'theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%' );
        }
        $p =$page->show();
        $this->assign( '_page', $p? $p: '' );
        $this->assign( '_total', $total );
        $options['limit'] = $page->firstRow.','.$page->listRows;

        $model->setProperty( 'options', $options );

        return $model->select();
    }

    /**
     * 将数据库获取的video数据得到detai并格式化lists
     *
     * @author susy<susy.liang@ilongyuan.com.cn>
     * @param unknown
     * @return
     */
    protected function lists_format( $videos, $filter_map = array( 'id', 'title', 'thumb', 'pre_uri', 'uri', 'time', 'detail', 'create_time', 'game_id', 'game', 'uid', 'user', 'statis', 'tags', 'action', 'icons', 'dpi_height', 'dpi_width', 'dpi_levels' ), $toFormat=true ) {
        $item = array();
        if ( !$videos ) {
            return $item;
        }

        $uid = is_login( 1 );
        $filter_game_map = array(
            'id', 'name', 'pic', 'cover', 'logo'
        );
        $vEvent = A( 'Api/Video', 'Event' );
        $specConf = C( 'IMAGE_UPLOAD_SPEC' );

        $service = D( 'Common/Video', 'Service' );
        $videos = array_map( 'intval', $videos );
        $where =  array( 'id'=>array( 'in', $videos ) );
        $res = $service->where( $where )->select();
        foreach ( $res as $value ) {
            $vEvent::$STATIC['ovideo'][$value['id']] = $value;
        }

        foreach ( $videos as $video_id ) {
            $video = $vEvent->detail( $video_id, $uid );
            if ( $video ) {
                $video = field_filter( $video, $filter_map );
                $video['game'] && $video['game'] = field_filter( $video['game'], $filter_game_map );

                //$this->timestamp = $video['create_time'];
                $video['time'] = $this->int2time($video['time']);
                $video['timestamp'] = $video['create_time'];

                if ( $toFormat ) {
                    $video['timestamp'] = $video['create_time'];
                    $video['create_time'] = unixtime_format( $video['create_time'] );
                }

                //remove 规格图 by susy.liang at 2015/8/13
               /* foreach ( $specConf as $key => $value ) {
                    $video['thumb_'.$key] = getThumb( $video['thumb'], $key );
                }*/
                //end
                $item[] = $video;
            }
        }
        return $item;
    }

    // 数据格式化 只保留需要的数据
    protected function field_filter( $data, $filter_map ) {
        if ( !$data ) {
            return;
        }
        foreach ( $data as $key => $value ) {
            if ( !in_array( $key, $filter_map ) ) {
                unset( $data[$key] );
            }
            else if ( !isset( $value ) ) {
                    $data[$key] = '';
                }
        }
        return $data;
    }

    /**
     * 获取所有用户昵称列表
     *
     * @param string  $keyword 已keyword开始的Nickname
     * @author susy<susy.liang@ilongyuan.com.cn>
     */
    public function userList() {

        $map = array();

        $keyword = I( 'keyword', '' );
        if ( $keyword )
            $map['nickname'] = array( 'like', $keyword.'%' );

        $user = A( 'Api/User', 'Event' )->lists( $map );

        $this->ajaxReturn( array( 'state'=>0, 'info'=>'操作成功', 'data'=>$ulists ) );
    }

    /**
     * 获取所有广告列表
     *
     * @param string  $code 广告位标识
     * @author zhaowei
     */
    protected function getAds( $code ) {
        return A( 'Api/Ad', 'Event' )->lists( $code );
    }

    private function int2time($time){
        $time = intval($time);
        $m = floor($time / 60);
        $s = floor(($time - $m*60)%60);
        return sprintf('%02d', $m).':'.sprintf('%02d', $s);
    }

    protected function _paging($p, $pageCount, $url, $urlParam) {
        $pageTemplate = C('PAGING_CONFIG')['LINK'];
        if ($pageCount <= 1) {
            return '';
        }
        $html = '';

        $html .= C('PAGING_CONFIG')['PREFIX'];
        $start = $p > 3 ? $p - 2 : 1;
        $end = $start + 5 - 1;
        if ($end > $pageCount) {
            $start = $pageCount - 4;
        }
        $start = $start > 0 ? $start : 1;

        for ($i = $start; $i <= $end && $i <= $pageCount; $i++) {
            $pageStr = $pageTemplate;

            $search = ['%CLASS%', '%LINK%', '%TEXT%'];
            $urlParam['p'] = $i;
            $link = U($url, $urlParam);
            $replace = ['', $link, $i];
            if ($i == $p) {
                $replace[0] = 'active';
            }
            $pageStr = str_replace($search, $replace, $pageStr);

            $html .= $pageStr;
        }
        if ($p < $pageCount) {
            $pageStr = $pageTemplate;

            $search = ['%CLASS%', '%LINK%', '%TEXT%'];
            $urlParam['p'] = $p + 1;
            $link = U($url, $urlParam);
            $replace = ['next', $link, '下一页'];
            $pageStr = str_replace($search, $replace, $pageStr);
            $html .= $pageStr;
        }
        $html .= C('PAGING_CONFIG')['SUFFIX'];
        return $html;
    }

    /**
     * 跨域请求
     * @author liubo <liubo@ilongyuan.com.cn>
     * @return [type] [description]
     */
    protected function _allow_origin() {
        $origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : '';

        if(preg_match('/66play\.com$/', $origin)) {
            header('Access-Control-Allow-Origin:'.$origin);
            header('Access-Control-Allow-Credentials:true');
            header('Access-Control-Allow-Headers:x-requested-with,content-type');
        }
    }
}